<script setup lang="ts">
import LogisticsApi from "@/api/logistics/index";
import { LogisticsStore } from "@/store/modules/logistics";
import { AnnouncementInfo } from "@/api/logistics/model";
import { ref, onMounted, computed } from "vue";
import { exportExcel } from "@/utils/exportTable"

const logisticsStore = LogisticsStore();
let showEditWindow = ref(false);
let isAddMode = ref(false);
let announcementStore: AnnouncementInfo[] = logisticsStore.announcement;
// 根据多少条数据分页
let limit = ref(10);
// 当前页
let page = ref(1);
// 搜索设备名称
let searchE = ref("");
// 获取表的数据
const getAnnouncements = () => {
  return LogisticsStore().getAnnouncementInfo();
};
const emptyData: AnnouncementInfo = {
  id: 0,
  title: "",
  content: "",
  category: "event",
  createdAt: new Date()
};
// 提供可选值给下拉列表
const statusList = ["emergency", "event", "rules_update"];

let newData = ref(emptyData);
let oldData = ref(emptyData);

const dataRules = computed((): {
  createdAt: { trigger: string; required: boolean }[];
  title: { trigger: string; required: boolean }[];
  category: { trigger: string; required: boolean }[];
  content: { trigger: string; required: boolean }[]
} => {
  return {
    title: [
      {
        required: true,
        trigger: "blur"
      }
    ],
    category: [
      {
        required: true,
        trigger: "blur"
      }
    ],
    content: [
      {
        required: true,
        trigger: "blur"
      }
    ],
    createdAt: [
      {
        required: false,
        trigger: "blur"
      }
    ]
  };
});
const showFormWindow = (addMode: boolean) => {
  isAddMode.value = addMode;
  showEditWindow.value = true;
};
const confirmData = () => {
  newData.value.createdAt = formatDate(newData.value.createdAt);
  if (isAddMode.value) {
    newData.value.id = 0;
    LogisticsApi.insertAnnouncement(newData.value).then((r) => {
      getAnnouncements().then((r) => {
        ElMessage.success("添加成功");
        showEditWindow.value = false;
      });
    });
  } else
    LogisticsApi.updateAnnouncement(newData.value).then((r) => {
      getAnnouncements().then((r) => {
        ElMessage.success("更新成功");
        showEditWindow.value = false;
      });
    });
};
const resetData = () => {
  newData.value = toIndependent(oldData.value);
};
const clearData = () => {
  newData.value = toIndependent(emptyData);
};
const handleEdit = (index: number, row: AnnouncementInfo[]) => {
  oldData.value = toIndependent(row);
  newData.value = toIndependent(oldData.value);
  console.log(newData);
  showFormWindow(false);
};
const handleDelete = (index: number, row: AnnouncementInfo) => {
  announcementStore.length = announcementStore.length - 1;
  LogisticsApi.deleteAnnouncement(row.id).then((r) => {
    getAnnouncements().then((r) => {
      ElMessage.success("删除成功");
    });
  });
};
const toIndependent = (json: object) => {
  return JSON.parse(JSON.stringify(json));
};
// 显示的表格
const filterTableData = computed(() => {
  return announcementStore.filter((data, index) => {
    // 编号从1开始
    index += 1;
    let result = true;
    // 搜索过滤
    result =
      !searchE.value ||
      data.title.toLowerCase().includes(searchE.value.toLowerCase());
    // 翻页实现
    result =
      result &&
      index <= page.value * limit.value &&
      index > (page.value - 1) * limit.value;
    return result;
  });
});
// 导出的数据
const thisDataToExcel = () => {
  return announcementStore.filter((data, index) => {
    // 编号从1开始
    index += 1;
    data.createdAt = formatDate(data.createdAt)
    data.id = index;
    return true;
  });
}
// 表格日期格式化
const formatTableDate = (row, column) => {
  // 获取单元格数据
  let data = row[column.property];
  if (data == null) {
    return null;
  }
  return formatDate(data);
};
// 日期格式化实现
const formatDate = (data) => {
  let dt = new Date(data);
  return dt.toLocaleString().replaceAll("/", "-");
};
onMounted(() => {
  getAnnouncements();
});
</script>

<template>
  <div class="announcement1">
    <el-button type="success" class="addDataBtn" @click="showFormWindow(true)"
    >添加数据
    </el-button>
    <el-button type="warning" class="addDataBtn" @click="exportExcel(thisDataToExcel(), ['id','title','category','content','createdAt'],['编号','标题','分类','内容','创建时间'],'公告表' + new Date().toLocaleString() + '.xlsx')"
    >导出数据
    </el-button>
    <el-table
      :data="filterTableData"
      style="width: 100%; margin-bottom: 20px; z-index: 0"
      row-key="id"
      border
      default-expand-all
      id="announcementTable"
    >
      <el-table-column label="编号" min-width="110">
        <template #default="scope">
          {{ scope.$index + 1 + (page - 1) * limit }}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" sortable min-width="180" />
      <el-table-column prop="category" label="分类" min-width="180" sortable />
      <el-table-column prop="content" label="内容" min-width="180" sortable />
      <el-table-column
        prop="createdAt"
        label="创建时间"
        :formatter="formatTableDate"
        min-width="240"
        sortable
      />
      <el-table-column label="操作" width="140">
        <template #header>
          <el-input v-model="searchE" placeholder="搜索设备名称" />
        </template>
        <template #default="scope">
          <el-button
            type="warning"
            size="small"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-model:limit="limit"
      v-model:page="page"
      v-model:total="announcementStore.length"
    />
    <!--    添加与修改公用弹窗-->
    <el-dialog
      v-model="showEditWindow"
      :title="isAddMode ? '新增' : '编辑'"
      width="500"
    >
      <el-form label-width="85" :model="newData" :rules="dataRules">
        <el-form-item label="标题：" prop="title">
          <el-input v-model="newData.title" :placeholder="oldData.title" />
        </el-form-item>
        <el-form-item label="内容：" prop="content">
          <el-input
            type="textarea"
            v-model="newData.content"
            size="large"
            :placeholder="oldData.content"
          />
        </el-form-item>
        <el-form-item label="类别：" prop="category">
          <el-select v-model="newData.category" placeholder="event">
            <el-option v-for="i in statusList" :key="i" :label="i" :value="i" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间：" prop="createdAt">
          <el-date-picker
            type="datetime"
            v-model="newData.createdAt"
            :placeholder="oldData.createdAt"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="confirmData()">确认</el-button>
          <el-button v-show="!isAddMode" type="warning" @click="resetData()"
          >重置
          </el-button
          >
          <el-button type="danger" @click="clearData()">清空</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.announcement1 {
  padding-top: 10px;
}

.addDataBtn {
  border-radius: 8px 8px 0 0;
}
</style>
